<template>
  <!--    <div>客户端档案挂接</div>-->
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <fileTrees @handleNodeClick="onTreeClick" :tableHeight="treeHeight" :isnoClick="isnoClick" :menuId="menuId">
        </fileTrees>
      </el-col>
      <el-col :span="20" :xs="24" v-show="isShowTable">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="批次号" prop="batchNum">
            <el-input v-model="queryParams.batchNum" placeholder="请输入批次号" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8" ref="refbut">
          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-upload2"
              v-show="subStr == categoryType && (subStr == 'F' || subStr == 'X')" @click="handleImport()">目录导入</el-button>
            <el-button type="info" plain icon="el-icon-upload2"
              v-show="subStr == categoryType && (subStr == 'X' || subStr == 'V')"
              @click="handleImportFolder()">案卷目录导入</el-button>
          </el-col>
          <el-col :span="1.5" v-show="subStr == 'V'">
            <el-button type="primary" plain icon="el-icon-printer" @click="handleImportFile()">卷内件导入</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="DataList" :height="tableHeight">
          <el-table-column label="序号" type="index" :index="table_index" width="55" align="center" prop="id" />
          <el-table-column label="批次号" align="center" prop="batchNum" :show-overflow-tooltip="true" />
          <el-table-column label="导入详情" prop="msg" align="center" :show-overflow-tooltip="true" />
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              {{ scope.row.state == '0' ? '成功' : '失败' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="250">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="viewDetail(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 用户导入对话框 -->
    <dataImport :upload="upload" @uploadCancel="uploadCancelTap" @importTemplate="importTemplateTap"
      @uploadFile="uploadFile" @submitFileForm="submit"></dataImport>

    <!-- 导入匹配页 -->
    <importMatch :match="match" ref="matchRef" @matchCancel="matchCancelTap" @submitMatch="submitMatch"></importMatch>

    <!-- 查看详情 -->
    <el-dialog title="日志详情" :visible.sync="detailOpen" width="50%" append-to-body :before-close="handleClose">
      <div style="margin: 1%; padding-bottom: 1%">
        <div class="first">
          <div style="display: flex; width: 80%">
            <span>批次号：{{ detailForm.batchNum }}</span>
            <span>失败条数：{{ detailForm.failNum }}</span>
            <span>成功条数：{{ detailForm.successNum }}</span>
          </div>
          <div style=" line-height: 50px; height: 50px; margin: 1%;">
            <el-button type="primary" plain icon="el-icon-download" @click="exportExcel">导出</el-button>
          </div>
        </div>
        <el-table v-loading="detailLoading" :data="detaillist">
          <el-table-column label="序号" type="index" prop="id" />
          <el-table-column label="失败数据" prop="failData" :show-overflow-tooltip="true" />
          <el-table-column label="失败信息" prop="msg" :show-overflow-tooltip="true" />
        </el-table>
        <pagination v-show="detailTotal > 0" :total="detailTotal" :page.sync="detailParams.pageNum"
          :limit.sync="detailParams.pageSize" @pagination="getDetailList" />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import estimateTableHeight from '@/mixins/estimateTableHeight'
import treeHeight from '@/mixins/treeHeight'//计算左侧树的高度
import fileTrees from "@/components/fileTrees/index.vue"
import { getList, getLogList, getTitle, uploadList } from "@/api/archive/digitalizeReceive/catalogImport";
import { getLastIndexOf } from "@/utils";
import { getGroupTree } from "@/api/archive/archivesCategory";
import dataImport from "@/components/dataImportComponent/dataImport";
import importMatch from "@/components/dataImportComponent/importMatch";
//vue项目中element-tabel自动计算高度
export default {
  mixins: [treeHeight, estimateTableHeight], // 混入方法
  components: { fileTrees, dataImport, importMatch, },
  data() {
    return {
      menuId: '',
      isnoClick: true,
      isClickSave: true,
      DataList: [],
      // 表格数据
      list: null,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 显示搜索条件
      showSearch: true,
      isShowTable: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        batchNum: undefined
      },
      categoryType: '',
      subStr: '',
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
      },
      // 导入文件类型  件、卷、项目
      uploadType: null,
      // 表格表头
      xlsTitle: [],
      // 可导入项
      sysTitle: [],
      // 匹配参数
      match: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
      },
      file: null,

      // 查看详情
      detailOpen: false,
      detailParams: {
        pageNum: 1,
        pageSize: 10,
        id: undefined
      },
      detailLoading: true,
      detaillist: [],
      detailTotal: 0,
      detailForm: {}
    }
  },
  created() {
    this.menuId = this.$route.meta.menuId
  },
  methods: {
    table_index(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    // 树节点单击事件
    onTreeClick(data) {
      console.log(data)
      this.isnoClick = false;
      if (data.nodeType == null || data.nodeType == "t" || data.nodeType == "f") {
        this.isShowTable = false
        this.isnoClick = true;
        return;
      }
      this.isShowTable = true
      this.queryParams.sub_table_name = data.sub_table_name;
      this.queryParams.categoryCode = data.categoryId
      if (this.queryParams.sub_table_name != undefined) {
        this.subStr = getLastIndexOf(this.queryParams.sub_table_name);
        let stb = this.queryParams.sub_table_name;
        let stbArr = stb.split("_");
        if (stbArr[stbArr.length - 3] == 0) {
          this.categoryType = 'F'
        } else if (stbArr[stbArr.length - 3] == 1) {
          this.categoryType = 'V'
        } else if (stbArr[stbArr.length - 3] == 3) {
          this.categoryType = 'X';
        }
      } else {
        this.getGroupTreePost(data.categoryId);
      }
      this.getList();
    },
    //档案门类树门类根据categoryID回显
    getGroupTreePost(ID) {
      getGroupTree(ID).then(response => {
        this.responselist = response.data;
        if (response.data.type == "0") { //件
          this.queryParams.sub_table_name = response.data.fileTableName;
        } else if (response.data.type == "1") { //卷
          this.queryParams.sub_table_name = response.data.folderTableName;
        } else { //项目
          this.queryParams.sub_table_name = response.data.itemTableName;
        }
        this.subStr = getLastIndexOf(this.queryParams.sub_table_name);
        let stb = this.queryParams.sub_table_name;
        let stbArr = stb.split("_");
        if (stbArr[stbArr.length - 3] == 0) {
          this.categoryType = 'F'
        } else if (stbArr[stbArr.length - 3] == 1) {
          this.categoryType = 'V'
        } else if (stbArr[stbArr.length - 3] == 3) {
          this.categoryType = 'X';
        }
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.getList()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    getList() {
      this.loading = true
      getList(this.queryParams).then(response => {
        this.DataList = response.rows
        this.total = response.total
        this.loading = false
        this.isnoClick = true;
      })
    },

    // 导入按钮  组件/项目
    handleImport() {


      console.log(this.subStr, this.categoryType,"1")
      if (this.subStr == "F" && this.categoryType == "F") {
          this.upload.title = "件数据";
      }
      if (this.subStr == "X" && this.categoryType == "X") {
          this.upload.title = "项目数据";
      }
      if (this.subStr == "F") {
  
        this.upload.open = true;
        this.uploadType = 0
      } else {
        this.upload.open = true;
        this.uploadType = 3
      }
    },
    // 案卷导入
    handleImportFolder() {
      console.log(this.subStr, this.categoryType,"2")
      if (this.subStr == "X" && this.categoryType == "X") {
        this.upload.title = "项目案卷数据";
      }   
      if (this.subStr == "V" && this.categoryType == "V") {
        this.upload.title = "案卷数据";
      }  
      this.upload.open = true;
      if (this.subStr == 'X') {
        this.uploadType = 6
      } else {
        this.uploadType = 1
      }
    },
    //给组卷 卷内件导入
    handleImportFile() {
      this.upload.title = "卷内件数据";
      this.upload.open = true;
      this.uploadType = 0
    },
    // 关闭导入  /件/卷/项目
    uploadCancelTap() {
      this.upload.open = false;
      this.getList();
    },
    // 下载模板
    importTemplateTap() {
      this.form = {
        type: this.uploadType,
        categoryId: this.queryParams.categoryCode
      }
      if (this.uploadType == 0) {
        // console.log("卷内件下载模板")
        this.download('/archive/daImport/download?type=' + this.uploadType + "&categoryId=" + this.queryParams.categoryCode, {
        }, `fileData_template_${new Date().getTime()}.xlsx`)
      } else if (this.uploadType == 1 || this.uploadType == 6) {
        // console.log("案卷下载模板")
        this.download('/archive/daImport/download?type=' + this.uploadType + "&categoryId=" + this.queryParams.categoryCode, {
        }, `folderData_template_${new Date().getTime()}.xlsx`)
      } else {
        // console.log("项目下载模板")
        this.download('/archive/daImport/download?type=' + this.uploadType + "&categoryId=" + this.queryParams.categoryCode, {
        }, `itemData_template_${new Date().getTime()}.xlsx`)
      }
    },
    // 上传文件
    uploadFile(concent) {
      this.file = concent.file
      const formData = new FormData();
      formData.append("file", concent.file);
      formData.append("categoryId", this.queryParams.categoryCode);
      formData.append("type", this.uploadType);
      getTitle(formData).then(response => {
        console.log(response)
        this.xlsTitle = response.data.xlsTitle.map(item => {
          return {
            xlsNum: item.num,
            xlsName: item.name
          }
        })
        this.sysTitle = response.data.sysTitle.map(item => {
          return {
            name: item.fieldName,
            caption: item.fieldCaption,
            showType: item.showType,
            dataLength: item.dataLength,
            isNoEmpty: item.isNoEmpty,
            defaultValue: item.defaultValue,
            checkChongfu: item.checkChongfu
          }
        })
        this.$nextTick(() => {   //此函数执行时所有的DOM挂载和渲染都已完成
          this.$refs.matchRef.init(this.xlsTitle, this.sysTitle);     //获取子组件中init方法并将父组件数据传递给子组件
        });
      })
    },
    // 点击确认
    submit() {
      // console.log("打开匹配页")
      this.upload.open = false

    //  console.log(this.subStr, this.categoryType,this.uploadType&&this.uploadType==0)
      if (this.subStr == "F" && this.categoryType == "F") {
         this.match.title = "件导入";
      }
      if (this.subStr == "X" && this.categoryType == "X"&&this.uploadType==3) {
         this.match.title = "项目导入";
      }
      if (this.subStr == "X" && this.categoryType == "X"&&this.uploadType==6) {
         this.match.title = "项目案卷导入";
      }

      if (this.subStr == "V" && this.categoryType == "X"&&this.uploadType==0) {
         this.match.title = "卷内件导入";
      }
    
      this.match.open = true
      // this.$nextTick(() => {   //此函数执行时所有的DOM挂载和渲染都已完成
      //   this.$refs.matchRef.init(this.xlsTitle,this.sysTitle);     //获取子组件中init方法并将父组件数据传递给子组件
      // });
    },
    submitMatch(matchedData) {
      this.form = {
        categoryId: this.queryParams.categoryCode,
        state: 5,
        jsType: 2,
        colNames: matchedData
      }
      // console.log(this.subStr, this.uploadType, this.ids)
      if (this.subStr == "F") {
        if (this.uploadType == 0) {
          this.form.type = this.uploadType
          // this.form.folderId = "-1"
        } else {
          this.form.type = this.uploadType
        }
      } else if (this.subStr == "V") {
        if (this.uploadType == 0) {
          this.form.type = 0
          if (this.ids == undefined || this.ids == null || this.ids == '') {
            this.form.folderId = "-1"
          } else {
            this.form.folderId = this.ids
          }
        } else {
          this.form.type = this.uploadType
        }
      } else {
        if (this.uploadType == 1 || this.uploadType == 6) {
          this.form.type = 1
          this.form.itemId = this.ids
        } else {
          this.form.type = this.uploadType
        }
      }
      const formData = new FormData();
      formData.append("file", this.file);
      formData.append("dataStr", JSON.stringify(this.form));
      uploadList(formData).then(response => {
        this.$modal.msgSuccess(response.msg);
        // this.match.open= false;
        this.getList()
      })
      this.match.open = false;
    },
    matchCancelTap() {
      this.match.open = false;
    },


    // 查看详情
    viewDetail(row) {
      this.detailOpen = true
      this.detailParams.id = row.id
      this.detailForm = row
      this.getDetailList()
    },
    getDetailList() {
      getLogList(this.detailParams).then(response => {
        this.detailLoading = false
        this.detaillist = response.rows
        this.detailTotal = response.total
      })
    },
    handleClose() {
      this.detailOpen = false
    },
    // 导出
    exportExcel() {
      this.download('archive/catalog/import/export', {
        ...this.detailParams
      }, `log_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style lang="scss" scoped>
.first {
  display: flex;

  span {
    line-height: 50px;
    height: 50px;
    display: flex;
    font-size: 14px;
    font-weight: bold;
    color: #606266;
    margin: 1%;
  }
}
</style>
